﻿<%@ WebHandler Language="C#" Class="SIPO.Web.AjaxHandler.Transaction.recExpensehandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;

using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.DataAccess.Administration;
using SIPO.Library.DomainObject.Administration;

using SIPO.Library.Enum;
using SIPO.Web.Support;

using Newtonsoft.Json.Linq;

namespace SIPO.Web.AjaxHandler.Transaction
{

    public class recExpensehandler : SIPO.Web.BaseHandler
    {
        recAlocationRepo recAlocationdal = new recAlocationRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        recExpenseRepo recExpenseDal = new recExpenseRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
        
        private string MethodName = string.Empty;
        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            //context.Response.Clear();
            //context.Response.Buffer = true;

            //System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            //string jsonString = string.Empty;            
            //jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            //JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            //sr.Close();
            //sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                //case ("insertnodialog"):
                //    context.Response.Write(InsertNoDialog(context));
                //    break;
                case ("update"):
                    System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
                    string jsonString = string.Empty;
                    jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                    JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);
                    sr.Close();
                    sr.Dispose();
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    sr = new System.IO.StreamReader(context.Request.InputStream);
                    jsonString = string.Empty;
                    jsonString = context.Server.UrlDecode(sr.ReadToEnd());
                    jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);
                    sr.Close();
                    sr.Dispose();
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
                
                
            }
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetData(HttpContext context)
        {
           
            string parameters = Helper.JqGridFilterToSQLParams(context);

          
            if(parameters!="")
                parameters += " AND (transactions.recExpense.IsActive = 1)";
            else
                parameters += " where (transactions.recExpense.IsActive = 1)"; 
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recExpense.Fields.ExpenseID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recExpense> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(recExpenseDal.SelectScalar(SQL.Function.Aggregate.Count, recExpense.Fields.ExpenseID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = recExpenseDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "recExpensehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }
        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            try{
                
                
                var data = context.Request.Form;
                var ReviewDate = context.Server.UrlDecode(data["txtReviewDate"]);
                recExpense obj = new recExpense();
                var expenseID = context.Server.UrlDecode(data["hfID"]);
                if (ReviewDate == ""|| ReviewDate == null)
                {
                    var transdate = context.Server.UrlDecode(data["txtTransDate"]);
                    var InvoiceNo = context.Server.UrlDecode(data["txtInvoiceNo"]);
                    var Alocation = context.Server.UrlDecode(data["ddlAlocation"]);
                    var Value = context.Server.UrlDecode(data["txtValue"]);
                    var Tujuan = context.Server.UrlDecode(data["txtTujuan"]);
                    var AlocationName = context.Server.UrlDecode(data["hfAlocationName"]);
                    var a = transdate.Substring(3, 3);
                    switch(a)
                    {
                        case ("Des") :
                           transdate = transdate.Replace("Des","Dec");
                            break;
                        case("Peb") :
                             transdate = transdate.Replace("Peb","Feb");
                        break;
                        case("Mei") :
                            transdate = transdate.Replace("Mei","May");
                            break;
                        case("Agu") :
                             transdate = transdate.Replace("Agu","Aug");
                        break;
                        case("Nop") :
                                transdate = transdate.Replace("Nop","Nov");
                        break;
                        case("Okt") :
                                transdate = transdate.Replace("Okt","Oct");
                        break;
                        default:
                        // do nothing
                        break;
                
                    }
                 
                    string[] alc = AlocationName.Split(',');
                    
                    obj.TransDate = Convert.ToDateTime(transdate);
                    obj.TransNo = InvoiceNo;
                    obj.TransDesc = Tujuan;
                    obj.TransAlocationID = Alocation;
                    if (alc.Length >1)
                    {
                        obj.TransAlocationName = alc.ElementAt(1).Trim();
                    }
                    else
                    {
                        obj.TransAlocationName = "";
                    }
                        obj.TransValues = Helper.ToDecimal(Value, System.Globalization.NumberStyles.Number, Helper.Culture.Indonesian);
                    obj.IsActive = true;
                }

                if (context.Request.Files.Count > 0)
                {
                    HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;
                    string FileName = string.Empty;
                    if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = hpf.FileName.Split(new char[] { '\\' });
                        FileName = files[files.Length - 1];
                    }
                    else
                    {
                        FileName = hpf.FileName;
                    }

                    byte[] datas = new byte[hpf.ContentLength];
                    hpf.InputStream.Position = 0;
                    hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                    obj.AttachFile = datas;
                    obj.AttachFileName = FileName;
                    
                    hpf.InputStream.Close();
                    hpf.InputStream.Dispose();
                    
                    if(expenseID == "" || expenseID == null)
                    {
                        obj.ExpenseID = recExpenseDal.GetMaxID();
                        obj.CreatedBy = base.UserLoggedIn;
                        obj.CreatedDate = DateTime.Now;
                        recExpenseDal.Save(obj);
                        helper.IsSuccess = true;
                        helper.Message = "Data berhasil di simpan !";
                    }
                    else
                    {
                        obj.UpdatedDate = DateTime.Now;
                        obj.UpdatedBy = UserLoggedIn;
                        obj.ExpenseID = Convert.ToInt32(expenseID);
                        recExpenseDal.Update(obj);
                        helper.IsSuccess = true;
                        helper.Message = "Data berhasil di ubah !";
                    }



                }
                else if (expenseID != "" && ReviewDate == "")
                {
                    recExpense recexpense = recExpenseDal.GetById(Convert.ToInt32(expenseID));
                    if (recexpense != null)
                    {
                        if (recexpense.AttachFile != null)
                        {
                            obj.UpdatedDate = DateTime.Now;
                            obj.UpdatedBy = UserLoggedIn;
                            obj.ExpenseID = Convert.ToInt32(expenseID);
                            recExpenseDal.UpdateWithoutFile(obj);
                            helper.IsSuccess = true;
                            helper.Message = "Data berhasil di ubah !";
                        }
                        else
                        {
                            obj.UpdatedDate = DateTime.Now;
                            obj.UpdatedBy = UserLoggedIn;
                            obj.ExpenseID = Convert.ToInt32(expenseID);
                            recExpenseDal.Update(obj);
                            helper.IsSuccess = true;
                            helper.Message = "Data berhasil di ubah !";
                        }
                       
                    }
                }
                else {

                    if (expenseID == "" || expenseID == null)
                    {
                        obj.ExpenseID = recExpenseDal.GetMaxID();
                        obj.CreatedBy = base.UserLoggedIn;
                        obj.CreatedDate = DateTime.Now;
                        recExpenseDal.Save(obj);
                        helper.IsSuccess = true;
                        helper.Message = "Data berhasil di simpan !";
                    }
                    else
                    {

                        obj.ExpenseID = Convert.ToInt32(expenseID);
                        obj.ReviewDate = Convert.ToDateTime(ReviewDate);
                        recExpenseDal.Review(Convert.ToDateTime(obj.ReviewDate).ToString("yyyyMMdd"), expenseID);
                        helper.IsSuccess = true;
                        helper.IsSuccess = true;
                        helper.Message = "Data berhasil di setujui !";
                    }
                }  
                }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "recExpensehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context,JObject jo)
        {
            JSONHelper helper = new JSONHelper();
            try
            {
                recExpense obj = new recExpense();
                obj.ExpenseID = (int)jo["ExpenseID"];
                obj.TransDesc = (string)jo["Tujuan"];
                obj.TransNo = (string)jo["InvoiceNo"];
                obj.TransValues = Convert.ToDecimal (jo["Values"].ToString().Replace(".",""));
                obj.TransAlocationID = (string)jo["AlocationID"];
                obj.TransAlocationName = (string)jo["AlocationName"];
                obj.UpdatedBy = base.UserLoggedIn;
                obj.UpdatedDate = DateTime.Now;

                recExpenseDal.Update(obj);
                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "recExpensehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context,JObject jo)
        {
            JSONHelper helper = new JSONHelper();
            try
            {
                var strId = (string)jo["ExpenseID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    recExpenseDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";

            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "recExpensehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }
		  

    }
}